<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="责任部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="enabledDeptOptions" :show-count="true" style="width: 300px;"
          placeholder="请选择责任部门" />
      </el-form-item>
      <el-form-item label="岗位">
        <!-- 下拉单选框，移除 multiple 属性即为单选 -->
        <el-select v-model="queryParams.postId" placeholder="请选择岗位">
          <!-- 选项列表，与之前用法一致 -->
          <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
            :disabled="item.status == 1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="风险类别" prop="riskCategory">
        <el-input v-model="queryParams.riskCategory" placeholder="请输入风险类别" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="风险名称" prop="riskName">
        <el-input v-model="queryParams.riskName" placeholder="请输入风险名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-input v-model="queryParams.riskLevel" placeholder="请输入风险等级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="责任人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择责任人">
          <el-option v-for="item in userOptions" :key="item.userId" :label="item.userName" :value="item.userId"
            :disabled="item.status == 1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['scyfFinal:riskControlNoticeCard:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['scyfFinal:riskControlNoticeCard:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['scyfFinal:riskControlNoticeCard:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['scyfFinal:riskControlNoticeCard:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="riskControlNoticeCardList" border style="width: 100%;" row-key="riskId"
      :row-style="{ height: 'auto' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="责任部门" align="center" prop="deptName" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="应急措施" align="center" prop="emergencyMeasures" />

      <el-table-column label="联系方式" align="center" prop="contactInformation" />
      <el-table-column label="风险类别" align="center" prop="riskCategory" />
      <el-table-column label="风险点" align="center" prop="riskPoint" />
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="风险名称" align="center" prop="riskName" />
      <el-table-column label="风险区域" align="center" prop="riskArea" />
      <el-table-column label="风险等级" align="center" prop="riskLevel" />
      <!-- 警示标志列（显示图片） -->
      <el-table-column label="警示标志" align="center" prop="warningSign">
        <template slot-scope="scope">
          <!-- 路径存在就显示图片，不存在则空着 -->
          <img v-if="scope.row.warningSign" :src="scope.row.warningSign" alt="警示标志"
            style="width: 80px; height: 60px; object-fit: cover;">
        </template>
      </el-table-column>

      <!-- 危害标识列（显示图片） -->
      <el-table-column label="危害标识" align="center" prop="hazardIdentification">
        <template slot-scope="scope">
          <img v-if="scope.row.hazardIdentification" :src="scope.row.hazardIdentification" alt="危害标识"
            style="width: 80px; height: 60px; object-fit: cover;">
        </template>
      </el-table-column>

      <el-table-column label="风险要素" align="center" prop="riskElements" />
      <el-table-column label="事故类型" align="center" prop="accidentType" />
      <el-table-column label="责任人" align="center" prop="userName" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['scyfFinal:riskControlNoticeCard:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['scyfFinal:riskControlNoticeCard:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 新增或修改风险管控告知卡对话框  -->
     
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" inline>
        <el-form-item label="归属部门" prop="deptId" class="form-item-col">
          <treeselect v-model="form.deptId" :options="enabledDeptOptions" :show-count="true" placeholder="请选择归属部门"
            @select="handleNodeClick" style="width: 240px;" />
        </el-form-item>
        <el-form-item label="岗位">
          <!-- 下拉单选框，移除 multiple 属性即为单选 -->
          <el-select v-model="form.postId" placeholder="请选择岗位">
            <!-- 选项列表，与之前用法一致 -->
            <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
              :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item>
        <!-- 第二行：责任人 + 联系方式 -->
        <el-form-item label="责任人" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择责任人">
            <el-option v-for="item in userOptions" :key="item.userId" :label="item.userName"
              :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInformation" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.contactInformation" placeholder="请输入内容" />
        </el-form-item>

        <!-- 第三行：风险类别 + 风险点 -->
        <el-form-item label="风险类别" prop="riskCategory" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.riskCategory" placeholder="请选择风险类别" />
        </el-form-item>
        <el-form-item label="风险点" prop="riskPoint" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.riskPoint" placeholder="请选择" />
        </el-form-item>

        <!-- 第四行：编码 + 风险名称 -->
        <el-form-item label="编码" prop="code" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="风险名称" prop="riskName" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.riskName" placeholder="请输入风险名称" />
        </el-form-item>

        <!-- 第五行：风险区域 + 风险等级 -->
        <el-form-item label="风险区域" prop="riskArea" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.riskArea" placeholder="请选择所在区域" />
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.riskLevel" placeholder="请选择风险等级" />
        </el-form-item>

        <!-- 第六行：警示标志 + 危害标识 -->
        <el-form-item label="警示标志" prop="warningSign" class="form-item-col">
          <!-- 图片上传组件 -->
          <el-upload class="avatar-uploader" action="" :http-request="uploadFile" :show-file-list="false"
            :on-success="warningSignSuccess" :on-error="handleUploadError" :before-upload="beforeUpload">
            <!-- 显示已上传的图片或默认图标 -->
            <img v-if="warningSign" :src="warningSign" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="危害标识" prop="hazardIdentification" class="form-item-col">
          <!-- 图片上传组件 -->
          <el-upload class="avatar-uploader" action="" :http-request="uploadFile" :show-file-list="false"
            :on-success="hazardIdentificationSuccess" :on-error="handleUploadError" :before-upload="beforeUpload">
            <!-- 显示已上传的图片或默认图标 -->
            <img v-if="hazardIdentification" :src="hazardIdentification" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <!-- 第七行：风险要素 + 事故类别 -->
        <el-form-item label="风险要素" prop="riskElements" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.riskElements" placeholder="请选择风险要素" />
        </el-form-item>
        <el-form-item label="事故类别" prop="accidentType" class="form-item-col">
          <el-input style="width: 240px;" v-model="form.accidentType" placeholder="请选择事故类别" />
        </el-form-item>

        <!-- 第八行：应急措施（独占一行，宽度自适应） -->
        <el-form-item label="应急措施" prop="emergencyMeasures" class="form-item-full">
          <el-input v-model="form.emergencyMeasures" placeholder="请输入内容" type="textarea" :rows="2" />
        </el-form-item>

        <!-- 第九行：后果（独占一行，宽度自适应） -->
        <el-form-item label="后果" prop="consequence" class="form-item-full">
          <el-input v-model="form.consequence" placeholder="请输入后果" type="textarea" :rows="2" />
        </el-form-item>

        <!-- 第十行：管控措施（独占一行，宽度自适应） -->
        <el-form-item label="管控措施" prop="controlMeasures" class="form-item-full">
          <el-input style="width: 100%;" v-model="form.controlMeasures" placeholder="请输入内容" type="textarea" :rows="2" />
        </el-form-item>

        <!-- 第十一行：告知卡图片 -->
        <el-form-item label="告知卡图片" prop="noticeCardPicture" class="form-item-full">
          <el-upload class="file-uploader" action="" :http-request="uploadFile" :show-file-list="true"
            :on-success="noticeCardPictureSuccess" :on-error="handleUploadError" :before-upload="beforeUpload">
            <!-- 上传按钮 -->
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- 提示文本 -->
            <div slot="tip" class="el-upload__tip">
              文件大小不超过 1MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>



      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listRiskControlNoticeCard, getRiskControlNoticeCard,
  delRiskControlNoticeCard, addRiskControlNoticeCard,
  updateRiskControlNoticeCard, getPostList, getUserList, handleCustomDownload
} from "@/api/scyfFinal/riskControlNoticeCard";
import { deptTreeSelect } from "@/api/system/user";
// 导入组件和样式
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  //在 components 中注册组件（注意组件名大小写）
  components: {
    // 注册后，模板中可使用 <treeselect> 标签
    Treeselect
  },
  name: "RiskControlNoticeCard",
  data() {
    return {
      //图片上传保存路径
      imageUrl: '',
      warningSign: '',
      hazardIdentification: '',
      noticeCardPicture: '',
      //责任人
      userOptions: [],
      // 岗位选项
      postOptions: [],
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 所有部门树选项
      deptOptions: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 风险管控告知卡表格数据
      riskControlNoticeCardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        postId: null,
        userId: null,
        riskCategory: null,
        code: null,
        riskName: null,
        riskLevel: null,
        deptId: undefined
      },
      // 表单参数
      form: {
        riskId: null,
        deptId: null,
        deptName: null,
        postId: null,
        postName: null,
        userId: null,
        userName: null,
        contactInformation: null,
        riskCategory: null,
        riskPoint: null,
        code: null,
        riskName: null,
        riskArea: null,
        riskLevel: null,
        warningSign: null,
        hazardIdentification: null,
        riskElements: null,
        accidentType: null,
        emergencyMeasures: null,
        consequence: null,
        controlMeasures: null,
        noticeCardPicture: null,
        postId: null,
      },
      // 表单校验
      rules: {
      }
    };
  },

  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getUserList();
    this.getList();
    this.getDeptTree();
    this.getPostList();

  },
  methods: {
    /** 图片上传 */
    uploadFile(params) {
      handleCustomDownload(params)
    },
    // warningSignSuccess上传成功回调
    warningSignSuccess(response) {
      console.log("上传成功回调");
      console.log(response);
      if (response.code === 200) {
        this.warningSign = response.data.url;
        this.form.warningSign = response.data.url;
        this.$message.success('上传成功');
        console.log("图片URL：" + this.imageUrl);
      } else {
        this.$message.error('上传失败：' + response.msg);
      }
    },
    // hazardIdentificationSuccess上传成功回调
    hazardIdentificationSuccess(response) {
      console.log("上传成功回调");
      console.log(response);
      if (response.code === 200) {
        this.hazardIdentification = response.data.url;
        this.form.hazardIdentification = response.data.url;
        this.$message.success('上传成功');
        console.log("图片URL：" + this.hazardIdentification);
      } else {
        this.$message.error('上传失败：' + response.msg);
      }
    },

    // noticeCardPictureSuccess上传成功回调
    noticeCardPictureSuccess(response) {
      console.log("上传成功回调");
      console.log(response);
      if (response.code === 200) {
        this.noticeCardPicture = response.data.url;
        this.form.noticeCardPicture = response.data.url;
        this.$message.success('上传成功');
        console.log("图片URL：" + this.noticeCardPicture);
      } else {
        this.$message.error('上传失败：' + response.msg);
      }
    },

    // 上传失败回调
    handleUploadError() {
      this.$message.error('上传失败，请重试');
    },
    // 上传前校验（格式、大小）
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isImage) {
        this.$message.error('只能上传图片文件！');
      }
      if (!isLt1M) {
        this.$message.error('图片大小不能超过1MB！');
      }
      return isImage && isLt1M;
    },
    /** 查询风负责人列表 */
    getUserList() {
      getUserList().then(response => {
        console.log("获取用户列表成功");
        console.log(response.rows);
        this.userOptions = response.rows;
      });
    },
    /** 查询岗位列表 */
    getPostList() {
      getPostList().then(response => {
        this.postOptions = response.rows;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.queryParams.deptId = data.id;
      console.log("点击的部门数据是：");
      console.log(data.label);
      this.form.responsibilityDepartment = data.label;
      console.log(this.form.responsibilityDepartment);
      this.handleQuery();
    },
    /** 查询风险管控告知卡列表 */
    getList() {
      this.loading = true;
      listRiskControlNoticeCard(this.queryParams).then(response => {
        this.riskControlNoticeCardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      window.location.reload();
    },
    // 表单重置
    reset() {
      this.form = {
        riskId: null,
        deptId: null,
        deptName: null,
        postId: null,
        postName: null,
        userId: null,
        userName: null,
        contactInformation: null,
        riskCategory: null,
        riskPoint: null,
        code: null,
        riskName: null,
        riskArea: null,
        riskLevel: null,
        warningSign: null,
        hazardIdentification: null,
        riskElements: null,
        accidentType: null,
        emergencyMeasures: null,
        consequence: null,
        controlMeasures: null,
        noticeCardPicture: null,
        postId: null,
      };
      this.resetForm("form");
      console.log("重置表单成功")
      console.log(this.form);
      
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log("查询参数是：");
      console.log(this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.riskId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加风险管控告知卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.riskId || this.ids
      getRiskControlNoticeCard(id).then(response => {
        this.form = response.data;
        this.warningSign = response.data.warningSign;
        this.hazardIdentification = response.data.hazardIdentification;
        console.log("获取数据成功");
        console.log(this.form);
        this.open = true;
        this.title = "修改风险管控告知卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log("提交数据是：");
          console.log(this.form);
          if (this.form.riskId != null) {
            updateRiskControlNoticeCard(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRiskControlNoticeCard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      window.location.reload();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.riskId || this.ids;
      console.log("删除的ID是：");
      console.log(ids);
      this.$modal.confirm('是否确认删除风险管控告知卡编号为"' + ids + '"的数据项？').then(function () {
        return delRiskControlNoticeCard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scyfFinal/riskControlNoticeCard/export', {
        ...this.queryParams
      }, `riskControlNoticeCard_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 关键：让单元格内容自动换行，并取消固定高度 */
::v-deep .el-table td,
::v-deep .el-table th {
  white-space: normal;
  /* 取消强制不换行 */
  word-break: break-all;
  /* 长单词/URL自动拆分换行 */
  line-height: 1.5;
  /* 行高适中，避免内容拥挤 */
  padding: 12px 10px;
  /* 适当内边距，增加可读性 */
  height: auto !important;
  /* 强制高度自适应 */
}
</style>



<style scoped>
/* 控制表单项列宽，实现两列布局 */
.form-item-col {
  width: 45%;
  margin-bottom: 15px;
}

/* 独占一行的表单项，宽度100% */
.form-item-full {
  width: 100%;
  margin-bottom: 15px;
}

/* 图片预览样式 */
.image-preview {
  margin-top: 10px;
}
</style>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  padding: 2px;
  /* 为内部元素预留边框空间 */
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #f0f0f0;
  /* 内部边框 */
  border-radius: 4px;
  background-color: #f4f4f4;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px solid #f0f0f0;
  /* 图片边框 */
  border-radius: 4px;
  object-fit: cover;
  /* 保持图片比例填充容器 */
  background-color: #e6f7ff;
  /* 图片加载前显示淡蓝色背景 */
}
</style>
